<?php
declare(strict_types=1);
namespace SixShop\Lakala\Controller\Api;

use app\model\User;
use SixShop\Core\Request;
use SixShop\Lakala\Config;
use SixShop\Lakala\Entity\ProfitShareReceiverEntity;
use SixShop\Lakala\Enum\ReceiverActionEnum;
use SixShop\Lakala\Enum\ReceiverStatusEnum;
use think\Response;
use function SixShop\Core\page_response;
use function SixShop\Core\success_response;
use function SixShop\Core\throw_logic_exception;

class ProfitShareReceiverController
{
    public function save(Request $request, ProfitShareReceiverEntity $entity, Config $config): Response
    {
        $data = $request->post();
        $data[ 'user_id'] = $request->userID;
        $data['org_code'] = $config->org_code;
        return success_response($entity->saveReceiver($data));
    }

    public function index(Request $request, ProfitShareReceiverEntity $entity, Config $config): Response
    {
        $userID = $request->userID;
        $params = ['user_id' => $userID];
        $effective = $entity->where([
            'user_id' => $userID,
            'status' => ReceiverStatusEnum::BOUND,
        ])->order('effective_time', 'desc')->find();
        $user = User::find($userID);
        return page_response(
            page: $entity->getReceiverList($params, $request->pageAndLimit()),
            data: [
                'effective' => $effective,
                'user' => [
                    'balance' => $user->balance,
                ],
                'config' => [
                    'profit_share_fee' => $config->profit_share_fee,
                    'profit_share_min' => $config->profit_share_min,
                    'profit_share_max' => $config->profit_share_max,
                ]
            ]
        );
    }

    public function read(int $id, Request $request, ProfitShareReceiverEntity $entity):Response
    {
        $params = ['user_id' => $request->userID, 'id' => $id];
        return success_response($entity->getReceiver($params));
    }

    public function update(int $id, Request $request, ProfitShareReceiverEntity $entity):Response
    {
        $params = [
            'user_id' => $request->userID,
            'id' => $id
        ];
        $data = $request->post([
            'receiver_name/s',
            'contact_mobile/s',
            'acct_type_code/s',
            'acct_open_bank_name/s',
            'acct_no/s',
        ]);
        $entity->where([
            'user_id' => $request->userID,
            'action' => ReceiverActionEnum::UPDATE,
            'status' => ReceiverStatusEnum::PENDING,
        ])->count() > 0 && throw_logic_exception('有待处理的变更申请，请勿重复提交');
        return success_response($entity->updateReceiver($params, $data));
    }
}